package com.bank.bank.customer.servcie.impl;


import com.bank.bank.common.base.exception.ServiceException;
import com.bank.bank.common.base.pojo.dto.CustomerAddParam;
import com.bank.bank.common.base.pojo.entity.Account;
import com.bank.bank.common.base.pojo.entity.Customer;
import com.bank.bank.common.base.pojo.vo.CustomerAddVO;
import com.bank.bank.common.base.pojo.vo.CustomerInfoVO;
import com.bank.bank.common.base.response.JsonResult;
import com.bank.bank.common.base.response.StatusCode;
import com.bank.bank.customer.client.AccountClient;
import com.bank.bank.customer.mapper.CustomerMapper;
import com.bank.bank.customer.servcie.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {
    //自动装配数据访问层[Dao层]
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public CustomerAddVO addCustomer(CustomerAddParam customerAddParam) {
        String phone = customerAddParam.getPhone();
        CustomerAddVO customerAddVO = customerMapper.getCustomerByPhone(phone);
        if (customerAddVO != null){//手机号被占用
            //自定义异常类
            throw new ServiceException(StatusCode.PHONE_ALREADY_EXISTS);
        }
        //未被占用
        Customer customer = new Customer();
        BeanUtils.copyProperties(customerAddParam, customer);
        customer.setCreatedAt(new Date());
        customerMapper.insertCustomer(customer);
        //查询该客户的所有信息
        customerAddVO = customerMapper.getCustomerByPhone(phone);

        return customerAddVO;
    }

    /**
     * 2.获取客户列表业务
     * @return
     */
    @Override
    public List<Customer> listCustomer() {
        List<Customer> customerList = customerMapper.getCustomerList();
        return customerList;
    }

    /**
     * 3.获取指定客户信息业务
     * @param customerId 客户id
     * @return
     */
    @Autowired
    private AccountClient accountClient;
    @Override
    public CustomerInfoVO getCustomerById(Integer customerId) {
        log.debug("业务层 customerId:{}", customerId);
        //1.使用customerId查询 本地数据 除了List<Account>都可获取
        CustomerInfoVO customerInfoVO = customerMapper.getCustomerById(customerId);
        //2.远程调用查询账户列表
        JsonResult jsonResult = accountClient.listAccounts(customerId);
        List<Account> datas=(List<Account>)jsonResult.getData();
        customerInfoVO.setAccounts(datas);
        return customerInfoVO;
    }
}












